package com.jxust.hr.security.config;

import cn.hutool.crypto.SecureUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

/**
 * 用户认证、权限
 */
@Component
@Slf4j
public class SelfUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //构建用户信息的逻辑(取数据库/LDAP等用户信息)

        SelfUserDetails userInfo = new SelfUserDetails();
        userInfo.setUsername(username);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        userInfo.setPassword(SecureUtil.md5("123"));// 模拟从数据库中获取的密码原为 123
//        userInfo.setPassword(encoder.encode("123"));// 模拟从数据库中获取的密码原为 123

        log.info("数据库中的密码为{}",SecureUtil.md5("123"));
        log.info("设置到userInfo中的密码为{}",userInfo.getPassword());
        Set authoritiesSet = new HashSet();
        GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ADMIN");// 模拟从数据库中获取用户角色
        authoritiesSet.add(authority);
        userInfo.setAuthorities(authoritiesSet);

        return userInfo;//$2a$10$vMspUrttZJSXyttU0qFMZ.vVUVBb2z2E5GmcgHvzjZIoyU1CVWCx2
    }
}